package com.mars.admin.service.impl;

import com.mars.admin.entity.SysPost;
import com.mars.admin.entity.SysQuest;
import com.mars.admin.mapper.SysPostMapper;
import com.mars.admin.mapper.SysQuestMapper;
import com.mars.admin.service.ISysPostService;
import com.mars.admin.service.ISysQuestService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.CacheableServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import static com.mars.admin.entity.table.SysQuestTableDef.SYS_QUEST;
import static com.mars.admin.entity.table.SysUserPostTableDef.SYS_USER_POST;

@Service
@CacheConfig(cacheNames = "quest")
public class SysQuestServiceImpl extends CacheableServiceImpl<SysQuestMapper, SysQuest> implements ISysQuestService {


    @Override
    public Page<SysQuest> selectQuestPage(Page<SysQuest> page, SysQuest quest) {
        QueryWrapper query = QueryWrapper.create()
                .select()
                .from(SYS_QUEST)
                .where(SYS_QUEST.IS_DELETED.eq(0));
        if (StringUtils.hasText(quest.getQuestName())) {
            query.and(SYS_QUEST.QUEST_NAME.like(quest.getQuestName()));
        }
        if (StringUtils.hasText(quest.getQuestCode())) {
            query.and(SYS_QUEST.QUEST_CODE.like(quest.getQuestCode()));
        }
        if (StringUtils.hasText(quest.getQuestDifficulty())) {
            query.and(SYS_QUEST.QUEST_DIFFICULTY.eq(quest.getQuestDifficulty()));
        }
        if (quest.getStatus() != null) {
            query.and(SYS_QUEST.STATUS.eq(quest.getStatus()));
        }

        query.orderBy(SYS_QUEST.CREATE_TIME.desc());

        return this.page(page, query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    public boolean deleteQuestById(Long postId) {

        // 删除问题
        return this.removeById(postId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    public boolean deleteQuests(Long[] postIds) {
        if (postIds == null || postIds.length == 0) {
            return false;
        }

        // 依次删除每个岗位及其关联数据
        for (Long postId : postIds) {
            deleteQuestById(postId);
        }

        return true;
    }
}
